from odoo import fields, models, api, _
from odoo.exceptions import UserError, ValidationError


class SelectProductWizard(models.TransientModel):
    _name = 'select.product.wizard'
    _description = 'Select Product Wizard'

    product_id = fields.Many2one('product.template', string='Product')
    parent_id = fields.Many2one('res.partner', string='supplier')
    unit_price = fields.Float('Unit Price', digits='Product Unit of Measure',
                              store=True, readonly=False)
    product_qty = fields.Integer('Quantity', default=1)
    purchase_requisition_id = fields.Many2one('purchase.requisition', string='Purchase Requisition')
    supplier_domain = fields.Many2many('res.partner', string='supplier', compute='_compute_supplier_domain')

    @api.constrains("unit_price")
    def _check_unit_price(self):
        if self.unit_price <= 0:
            raise ValidationError(_("The unit price must be greater than 0"))

    @api.constrains("product_qty")
    def _check_product_qty(self):
        if self.product_qty <= 0:
            raise ValidationError(_("The quantity must be greater than 0"))

    @api.onchange('parent_id')
    def _compute_unit_price(self):
        for res in self:
            if res.parent_id:
                for x in res.product_id.seller_ids:
                    if x.partner_id.id == res.parent_id.id.origin:
                        res.unit_price = x.price
                        break
            if res.unit_price <= 0:
                res.unit_price = 1  # 如果没有匹配的价格，默认设置为 0

    @api.onchange('product_id')
    def _compute_supplier_domain(self):
        if self.product_id:
            self.supplier_domain = self.product_id.seller_ids.mapped('partner_id').ids
            self.parent_id = self.supplier_domain[0] if self.supplier_domain else False

    def confirmation(self):
        if not self.parent_id:
            return {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'title': 'Error',
                    'message': _('Please maintain supplier information for product %s') % self.product_id.name,
                    'sticky': False,  # 设置为 False，表示通知不会一直显示
                    'timeout': 5000,  # 设置通知显示的时间（单位：毫秒），此处为 5 秒
                }
            }
        purchase_order = self.env['purchase.order'].sudo().create({
            'partner_id': self.parent_id.id,
            'date_order': self.purchase_requisition_id.requisition_date,
            'picking_type_id': self.env.ref('stock.picking_type_in').id,
            's_remark': self.purchase_requisition_id.remark
        })
        self.env['purchase.order.line'].sudo().create({
            'product_id': self.product_id.product_variant_id.id,
            'product_qty': self.product_qty,
            'product_uom': self.product_id.uom_id.id,
            'price_unit': self.unit_price,
            'name': self.product_id.name,
            'order_id': purchase_order.id,
        })
        # 将生成的采购单关联到采购申请
        self.purchase_requisition_id.state = 'done'
        self.purchase_requisition_id.write({'purchase_ids': [(4, purchase_order.id)]})
        return {
            'type': 'ir.actions.act_window',
            'name': 'Purchase Order',
            'res_model': 'purchase.order',
            'view_mode': 'form',
            'res_id': purchase_order.id,
            'target': 'current',
        }
